package com.mycjj.android.activity;

import java.io.File;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;

import com.edmodo.cropper.CropImageView;
import com.mycjj.android.R;
import com.mycjj.android.util.Constants;
import com.mycjj.android.util.ImageUtil;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;


public class CropperImageActivity extends BaseActivity {

	private static final int ROTATE_NINETY_DEGREES = 90;// 旋转角度

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_cropperimage);
		getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
		init();
	}

	private void init() {
		Intent intent = getIntent();
		String path = "file://" + intent.getStringExtra("path");
		Log.e("mark","CropperImageActivity target:" + path);

		final CropImageView cropImageView = (CropImageView) findViewById(R.id.cropImageView);
		findViewById(R.id.discard).setOnClickListener(
				new View.OnClickListener() {
					public void onClick(View v) {
						setResult(RESULT_CANCELED);
						finish();
					}
				});

		findViewById(R.id.roate_button).setOnClickListener(
				new View.OnClickListener() {
					public void onClick(View v) {
						cropImageView.rotateImage(ROTATE_NINETY_DEGREES);
					}
				});

		findViewById(R.id.save).setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				Bitmap croppedImage = cropImageView.getCroppedImage();
				//对裁切得到的bitmap 再次进行取缩略图
				Bitmap newBitmap = ImageUtil.getBitmapThumbnail(croppedImage, 100, 100);
				croppedImage.recycle();
				File file = ImageUtil.saveBitmapToSDcard(Constants.DATA_DIR,newBitmap, 100);
				Intent intent = new Intent();
				intent.putExtra("data", file.getPath());
				setResult(RESULT_OK, intent);
				finish();
			}
		});


		DisplayImageOptions options = new DisplayImageOptions.Builder()
				.showImageOnFail(R.drawable.ic_launcher)
				.showImageForEmptyUri(R.drawable.ic_empty)
				.bitmapConfig(Config.ARGB_8888)
				.imageScaleType(ImageScaleType.EXACTLY_STRETCHED).build();

		imageLoader.loadImage(path, options, new SimpleImageLoadingListener() {
			@Override
			public void onLoadingComplete(String imageUri, View view,
					Bitmap loadedImage) {
				cropImageView.setImageBitmap(loadedImage);
			}

			@Override
			public void onLoadingFailed(String imageUri, View view,
					FailReason failReason) {
				super.onLoadingFailed(imageUri, view, failReason);
			}
		});
	}

}
